package com.example.computer_exam_training_sys.mapper;

import com.example.computer_exam_training_sys.entity.UserMessage;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMessageMapper {
    
    @Insert("INSERT INTO user_messages (sender_id, receiver_id, message_type, title, content, status, " +
            "note_id, course_id, priority, publish_time, expire_time, create_time, update_time) " +
            "VALUES (#{senderId}, #{receiverId}, #{messageType}, #{title}, #{content}, #{status}, " +
            "#{noteId}, #{courseId}, #{priority}, #{publishTime}, #{expireTime}, #{createTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "messageId")
    void insert(UserMessage message);

    @Select("SELECT * FROM user_messages WHERE message_id = #{messageId}")
    UserMessage findById(Long messageId);

    @Select("SELECT * FROM user_messages WHERE receiver_id = #{receiverId} ORDER BY create_time DESC")
    List<UserMessage> findByReceiverId(Long receiverId);

    @Select("SELECT * FROM user_messages WHERE sender_id = #{senderId} ORDER BY create_time DESC")
    List<UserMessage> findBySenderId(Long senderId);

    @Select("SELECT * FROM user_messages WHERE message_type = #{messageType} AND (receiver_id = #{userId} OR receiver_id IS NULL) " +
            "ORDER BY create_time DESC")
    List<UserMessage> findPublishedMessages(@Param("messageType") String messageType, @Param("userId") Long userId);

    @Select("SELECT COUNT(*) FROM user_messages WHERE receiver_id = #{userId} AND status = 'PENDING'")
    int countPendingMessages(Long userId);

    @Update("UPDATE user_messages SET status = #{status}, update_time = NOW() WHERE message_id = #{messageId}")
    void updateStatus(@Param("messageId") Long messageId, @Param("status") String status);

    @Update("UPDATE user_messages SET title = #{title}, content = #{content}, status = #{status}, " +
            "note_id = #{noteId}, course_id = #{courseId}, priority = #{priority}, " +
            "publish_time = #{publishTime}, expire_time = #{expireTime}, update_time = NOW() " +
            "WHERE message_id = #{messageId}")
    void update(UserMessage message);

    @Delete("DELETE FROM user_messages WHERE message_id = #{messageId}")
    void delete(Long messageId);

    @Select("SELECT COUNT(*) FROM user_messages WHERE receiver_id = #{userId} AND status = 'PENDING'")
    int countUnreadMessages(Long userId);

    @Select("SELECT * FROM user_messages WHERE (sender_id = #{adminId} OR receiver_id = #{adminId}) " +
            "AND (#{messageType} IS NULL OR message_type = #{messageType}) " +
            "ORDER BY create_time DESC")
    List<UserMessage> findAllMessages(@Param("adminId") Long adminId, @Param("messageType") String messageType);
} 